﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
using Taurus.Platform.DTO;
using Taurus.Platform.Exception;
using System.Text.RegularExpressions;
using System.Threading;

namespace Taurus.Platform.Net
{
    /// <summary>
    /// 访问页面以及一些通用判定
    /// 2009-12-16 
    /// 吴鸣震
    /// </summary>
    public class Util
    {
        const string LOGIN_URL = "http://www.kaixin001.com/login/login.php?email={0}&password={1}";
        /// <summary>
        /// 用户访问页面
        /// </summary>
        /// <param name="user"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public static HtmlDocument AccessPage(UserAccount user, string url)
        {
            return AccessPage(user, url, "get");
        }
       
        public static HtmlDocument AccessPage(UserAccount user, string url, string method)
        {
            HtmlWebBuilder builder = new HtmlWebBuilder();
            HtmlWeb hw = builder.BulidHtmlWeb(user.Email);

            HtmlDocument doc = hw.Load(url, method);
            if (IsLogin(doc))
            {
                return doc;
            }
            else
            {
                if (Login(user, hw))
                {
                    return hw.Load(url);
                }
                else
                {
                    throw new LoginException();
                }
            }
        }
        
        /// <summary>
        /// 返回页数
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static int GetPageCount(HtmlDocument html)
        {
            return GetPageCount(html, 20);
        }
        public static int GetPageCount(HtmlDocument html,int size)
        {
            HtmlNodeCollection nc = html.DocumentNode.SelectNodes("//a[@class='fy']");
            if (nc != null)
            {
                foreach (var item in nc)
                {
                    if (item.InnerText.Trim() == "末页")
                    {
                        string xp = item.Attributes["href"].XPath;
                        int s = item.Attributes["href"].Value.LastIndexOf("start");
                        string start = item.Attributes["href"].Value.Substring(s + 6);
                        return int.Parse(start) / size + 1;
                    }
                }
            }

            return 1;
        }
        /// <summary>
        /// 用户身份验证
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public static bool Authenticated(UserAccount user)
        {
            HtmlWebBuilder builder = new HtmlWebBuilder();
            HtmlWeb hw = builder.BulidHtmlWeb(user.Email);
            return Login(user, hw);
        }
        /// <summary>
        /// 提取字符串中的数字
        /// </summary>
        /// <param name="par"></param>
        /// <returns></returns>
        public static int GetNumber(string par)
        {
            return Convert.ToInt32(Regex.Replace(par, @"[^\d]*", string.Empty));
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public static HtmlDocument Login(UserAccount user)
        {
            HtmlWebBuilder builder = new HtmlWebBuilder();
            HtmlWeb hw = builder.BulidHtmlWeb(user.Email);
            string url = string.Format(LOGIN_URL, user.Email, user.Password);
            return hw.Load(url, "post");
        }
        #region private
      
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="user"></param>
        /// <param name="hw"></param>
        /// <returns></returns>
        private static bool Login(UserAccount user, HtmlWeb hw)
        {
            string url = string.Format(LOGIN_URL, user.Email, user.Password);
            HtmlDocument doc = hw.Load(url, "post");
            HtmlNode title = doc.DocumentNode.SelectSingleNode("/html[1]/head[1]/title[1]");
            if (title == null)
            {
                //被开心网防外挂程序屏蔽了该账号
                return false;
            }
            if (title.InnerText.Trim() == "我的首页 - 开心网")
            {
               user.UID = CookieContainerManager.GetCookieValue(user.Email, new Uri(url), "_uid");
                return true;
            }
            return false;
        }
        /// <summary>
        /// 判断是否已经登录开心网
        /// </summary>
        /// <param name="doc"></param>
        /// <returns></returns>
        private static bool IsLogin(HtmlDocument doc)
        {
            if (doc.DocumentNode.SelectSingleNode("/html[1]") == null)
            {
                //当返回格式非html时候当做该用户已经登录
                return true;
            }
            return doc.DocumentNode.SelectSingleNode("/html[1]/head[1]/title[1]").InnerText.Trim() != "登录 - 开心网";
        }
        #endregion
    }
}
